/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.biviz.jgooglegears;

import java.applet.Applet;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.UUID;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import textbender.o.rhinohide.RhiWindow;

/**
 *
 * @author zhengyu.jin
 */
public class JGGStubApplet extends Applet {

    public static String APPLET_INST_UUID_KEY = "APPLET_INST_UUID";

    public class JGGStubInfo {

        public UUID appletUUID;
        public Applet applet;
        public RhiWindow window;
    }
    private static Hashtable<String, JGGStubInfo> jggStubInfoHT = new Hashtable();

    public static RhiWindow getWindowByUUID(String uuid) {
        return jggStubInfoHT.get(uuid).window;
    }

    public static Applet getAppletByUUID(String uuid) {
        return jggStubInfoHT.get(uuid).applet;
    }

    public static String[] getAllAppletUUIDs() {
        Enumeration<String> keysEnum = jggStubInfoHT.keys();
        if (jggStubInfoHT.size() > 0) {
            String[] returns = new String[jggStubInfoHT.size()];
            for (int i = 0; keysEnum.hasMoreElements(); i++) {
                returns[i] = keysEnum.nextElement();
            }
            return returns;
        }
        return null;
    }

    String jggsInfoKey;
    JGGStubInfo jggsInfo;

    @Override
    public void start() {
        jggsInfo = new JGGStubInfo();
        jggsInfo.appletUUID = UUID.randomUUID();
        jggsInfo.applet = this;
        jggsInfo.window = RhiWindow.createWindow( /*applet*/this);

        RhiWindow window = jggsInfo.window;
        jggsInfoKey = jggsInfo.appletUUID.toString();
        String cookie = (String) window.evalV("document.cookie");
        printMsg("Old document.cookie=" + cookie);
        cookie = APPLET_INST_UUID_KEY + "=" + jggsInfoKey + ";" + cookie;
        cookie = (String) window.evalV("document.cookie='" + cookie + "'");
        printMsg("New document.cookie=" + cookie);

        jggStubInfoHT.put(jggsInfoKey, jggsInfo);
        Enumeration<String> keyEnum = jggStubInfoHT.keys();
        for (; keyEnum.hasMoreElements();) {
            String key = keyEnum.nextElement();
            printMsg(key);
        }
    }

    @Override
    public void stop() {
        jggStubInfoHT.remove(jggsInfoKey);
    }

    private void printMsg(String message) {
        System.out.println(message);
    }
}

